<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import {
    addVirtualDeviceApi,
    DeviceStatusEnum,
    randomAddVirtualDeviceApi,
  } from '@/api/hc/virtualDevice';
  import { pageGetProductApi, Product } from '@/api/hc/iotProduct';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Select } from 'ant-design-vue';
  import { BasicForm, FormSchema } from '@/components/Form';
  import { Devices, excel2AddJson } from '@/api/hc/device';
  import { PageWrapper } from '@/components/Page';

  const deviceStatusList: { id: string; name: string }[] = [];
  for (let deviceStatusEnumKey in DeviceStatusEnum) {
    deviceStatusList.push({
      id: deviceStatusEnumKey,
      name: deviceStatusEnumKey,
    });
  }

  onMounted(() => {
    pageGetProduct();
  });

  const productList = ref<Product[]>([]);

  async function pageGetProduct() {
    const res = await pageGetProductApi({
      pageNum: 1,
      pageSize: 10000,
    });
    productList.value = res.list;
    console.log(res);
  }

  const { createMessage } = useMessage();

  let deviceList = ref<Devices[]>([]);
  const deviceColumns = [
    {
      title: 'batch',
      dataIndex: 'batch',
      key: 'batch',
    },
    {
      title: 'batteryId',
      dataIndex: 'batteryId',
      key: 'batteryId',
    },
    {
      title: 'deviceModel',
      dataIndex: 'deviceModel',
      key: 'deviceModel',
    },
    {
      title: 'hardwareId',
      dataIndex: 'hardwareId',
      key: 'hardwareId',
    },
    {
      title: 'hardwareVersion',
      dataIndex: 'hardwareVersion',
      key: 'hardwareVersion',
    },
    {
      title: 'imei',
      dataIndex: 'imei',
      key: 'imei',
    },
    {
      title: 'iotProtocol',
      dataIndex: 'iotProtocol',
      key: 'iotProtocol',
    },
    {
      title: 'iotServer',
      dataIndex: 'iotServer',
      key: 'iotServer',
    },
    {
      title: 'productKey',
      dataIndex: 'productKey',
      key: 'productKey',
    },
    {
      title: 'productionTime',
      dataIndex: 'productionTime',
      key: 'productionTime',
    },
    {
      title: 'sn',
      dataIndex: 'sn',
      key: 'sn',
    },
    {
      title: 'status',
      dataIndex: 'status',
      key: 'status',
    },
  ];

  const randAddSchemas: FormSchema[] = [
    {
      field: 'productId',
      label: '产品',
      slot: 'productId',
      defaultValue: null,
      colProps: {
        span: 8,
      },
    },
    {
      field: 'addDevicesSum',
      label: '随机生成数量',
      slot: 'addDevicesSum',
      defaultValue: 3,
      colProps: {
        span: 8,
      },
    },
  ];

  const excelAddSchemas: FormSchema[] = [
    {
      field: 'productId',
      label: '产品',
      slot: 'productId',
      defaultValue: null,
      colProps: {
        span: 8,
      },
    },
    {
      field: 'file',
      component: 'Upload',
      slot: 'file',
      label: '上传',
      colProps: {
        span: 8,
      },
      // rules: [{ required: true, message: '请选择上传文件' }],
      // componentProps: {
      //   api: uploadApi,
      // },
    },
  ];

  function randHandleSubmit(values: any) {
    randomAddVirtualDeviceApi({
      productId: values.productId,
      addDevicesSum: values.addDevicesSum,
    }).then((res) => {
      createMessage.error('randHandleSubmit' + res);
    });
  }

  function excelHandleSubmit(values: any) {
    console.log('values', values);
    const req = {
      file: values.file,
      data: {
        deviceModel: values.productId,
      },
    };
    excel2AddJson(req, (e) => {
      console.log(e);
    }).then((res) => {
      console.log(res);
      deviceList.value = res.data.data;
    });
  }

  function addAll() {
    deviceList.value.forEach((device: Devices) => {
      addVirtualDeviceApi(device).then((res) => {
        let status = '失败';
        if (res == 1) {
          status = '成功';
        }
        for (let i = 0; i < deviceList.value.length; i++) {
          const item = deviceList.value[i];
          if (item.sn === device.sn) {
            item.status = status;
            deviceList.value.splice(i, 1, item);
          }
        }
      });
    });
  }

  const handleBeforeUpload = (file, model, field) => {
    model[field] = file;
    // 阻止自动上传
    return false;
  };
</script>

<template>
  <PageWrapper>
    <BasicForm
      autoFocusFirstItem
      :labelWidth="200"
      :schemas="randAddSchemas"
      :actionColOptions="{ span: 24 }"
      @submit="randHandleSubmit"
      :show-reset-button="false"
      :submit-button-options="{
        text: '添加设备',
      }"
    >
      <template #productId="{ model, field }">
        <Select v-model:value="model[field]">
          <template v-for="item in productList" :key="item.id">
            <a-select-option :value="item.id">{{ item.name }}</a-select-option>
          </template>
        </Select>
      </template>
      <template #addDevicesSum="{ model, field }">
        <a-input v-model:value="model[field]" />
      </template>
    </BasicForm>

    <BasicForm
      autoFocusFirstItem
      :labelWidth="200"
      :schemas="excelAddSchemas"
      :actionColOptions="{ span: 24 }"
      @submit="excelHandleSubmit"
      :show-reset-button="false"
      :submit-button-options="{
        text: '生成表格',
      }"
    >
      <template #productId="{ model, field }">
        <Select v-model:value="model[field]" disabled>
          <template v-for="item in productList" :key="item.id">
            <a-select-option :value="item.id">{{ item.name }}</a-select-option>
          </template>
        </Select>
      </template>
      <template #file="{ model, field }">
        <a-upload
          :before-upload="
            ($event) => {
              handleBeforeUpload($event, model, field);
            }
          "
        >
          <a-button>
            <upload-outlined />
            Click to Upload
          </a-button>
        </a-upload>
      </template>
    </BasicForm>

    <a-table :dataSource="deviceList" :columns="deviceColumns">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'productId'">
          <a>
            <a-select v-model:value="record.productId" style="width: 120px" class="mr-2" disabled>
              <template v-for="(item, index) in productList" :key="index">
                <a-select-option :value="item.id">{{ item.name }}</a-select-option>
              </template>
            </a-select>
          </a>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a-button type="primary" danger>删除</a-button>
          </span>
        </template>
      </template>
    </a-table>
    <a-button type="primary" @click="addAll">添加表格设备</a-button>
  </PageWrapper>
</template>

<style scoped lang="less"></style>
